package com.hqyj.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.exception.CodeEnum;
import com.hqyj.exception.R;
import com.hqyj.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * jwt认证：验证token
 */
@Component
@Slf4j
public class JwtFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下⽂中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //定义不需要拦截的url
        String urls[] ={
                "/server-login/login/user",
                "/server-regist/register/user",
                "/server-goods-info/goods-info/goods",
                "/server-goods-info/goods-info/goods/2"
        };
        //获取当前请求url地址
        String url = request.getPath().value();

        boolean isNo = false;
        //判断当前请求url地址是否需要拦截
        for (String s:urls){
            if(url.equals(s)){
                isNo = true;
            }
        }
        //放行不需要拦截的url地址
        if (isNo){
            log.info("此url地址不需要拦截");
            return chain.filter(exchange);
        }else{//拦截
            log.info("开始验证token是否正确");
            String token =  request.getHeaders().getFirst("Authorization");
            //-------------第一步:验证请求体是否有token值------------
            //设置返回响应结果信息给前端
            ObjectMapper mapper = new ObjectMapper();
            DataBuffer data =null;
            if (StringUtils.isEmpty(token) ){
                log.info("token为空");
                //把响应数据转换成DataBuffer对象
                try {
                    data = response.bufferFactory().wrap(
                            mapper.writeValueAsBytes(
                                    R.error(CodeEnum.ERROR_TOKEN_NULL.MSG,
                                            CodeEnum.ERROR_TOKEN_NULL.CODE,
                                            null)));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                //把DataBuffer对象写入
                return response.writeWith(Mono.just(data));

            }
            //-------------第二步：验证token值是否正确---------------
            String id = JwtUtil.getAudience(token);
            if (id == null) {
                try {
                    data = response.bufferFactory().wrap(
                            mapper.writeValueAsBytes(
                                    R.error(CodeEnum.ERROR_TOKEN_INVALID.MSG,
                                            CodeEnum.ERROR_TOKEN_INVALID.CODE,
                                            null)));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                //把DataBuffer对象写入
                return response.writeWith(Mono.just(data));

            }
            //-------------第三步：验证token是否过期----------------
            //获取当前token的盐值
            String jwtSalt = JwtUtil.getClaimByName(token,"jwtSalt").asString();
            //验证token是否正确
            DecodedJWT decodedJWT = JwtUtil.verifyToken(token, jwtSalt);
            if (decodedJWT == null) {
                log.info("token超时");
                try {
                    data = response.bufferFactory().wrap(
                            mapper.writeValueAsBytes(
                                    R.error(CodeEnum.ERROR_TOKEN_TIMEOUT.MSG,
                                            CodeEnum.ERROR_TOKEN_TIMEOUT.CODE,
                                            null)));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                //把DataBuffer对象写入
                return response.writeWith(Mono.just(data));

            }

        }
        log.info("token验证通过");
        //合法请求，放行
        return chain.filter(exchange);
    }
    /*
     * 返回值表示当前过滤器的顺序(优先级)，数值越⼩，优先级越⾼
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
